package com.nonintrusive.client.tabs.history;

import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;

import com.nonintrusive.client.GlobalNonIntrusive;
import com.nonintrusive.client.Question;
import com.nonintrusive.client.database.ClientDB;
import com.nonintrusive.client.send.R;

public class HistoryActivity extends ListActivity {
	private ArrayList<Question> mQuestions;
	private HistoryQuestionAdapter mAdapter;
	private long mLastUpdate;
	private Handler mHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);

		mLastUpdate = 0;
		mHandler = new Handler();

		ListView list = (ListView) findViewById(android.R.id.list);
		mQuestions = GlobalNonIntrusive.allQuestions = new ArrayList<Question>();

		mAdapter = GlobalNonIntrusive.allQAdapter = new HistoryQuestionAdapter(
				this, R.layout.question_item, mHandler);
		list.setAdapter(mAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		final ArrayList<Question> questions = mQuestions;
		final HistoryQuestionAdapter adapter = mAdapter;
		new Thread(new Runnable() {
			@Override
			public void run() {
				Cursor cursor = managedQuery(ClientDB.CONTENT_URI, null,
						ClientDB.TIMESTAMP + " > " + mLastUpdate, null, null);
				mLastUpdate = System.currentTimeMillis();

				int id_i = cursor.getColumnIndex(ClientDB.QUESTION_ID);
				int message_i = cursor.getColumnIndex(ClientDB.MESSAGE);
				int myQ_i = cursor.getColumnIndex(ClientDB.IS_MY_QUESTION);
				int isAnswered_i = cursor.getColumnIndex(ClientDB.IS_ANSWERED);
				
				while (cursor.moveToNext()) {
					final Question item = new Question();
					item.id = cursor.getInt(id_i);
					if (questions.contains(item))
						continue;
					item.message = cursor.getString(message_i);
					if (cursor.getInt(myQ_i) == 1)
						item.isMine = true;
					else
						item.isMine = false;
					
					if (cursor.getInt(isAnswered_i) == 1)
						item.isAnswered = true;
					else
						item.isAnswered = false;
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							questions.add(item);
							adapter.notifyDataSetChanged();
						}
					});
				}
			}
		}).start();
	}
}
